import { validationResult } from 'express-validator'

export default (validators) => {
  let middleware = async (req, res, next) => {
    for (let item of validators) {
      // 手动运行验证
      const result = await item.run(req)

      if (result.errors.length) break
    }

    // 拿到请求的值，进行验证，验证通过，调用next， 未通过，直接返回 业务层自定义 错误信息

    const validRes = validationResult(req)

    if (validRes.errors.length !== 0) {
      res.json({
        code: -1,
        data: null,
        message: `${validRes.errors[0].path}-${validRes.errors[0].msg}`
      })
      return
    }

    next()
  }

  return middleware
}
